package com.hwtx.form.domain.ds;

import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.function.Supplier;

@Service
public class DataSourceService {

    @Resource
    private DynamicDataSource dynamicDataSource;

    public static Object invoke(Object ds, Supplier<Object> supplier) {
        if (ds != null && StringUtils.isNotBlank(ds.toString())) {
            try {
                DataSourceContextHolder.checkDataSourceKey(ds.toString());
                return supplier.get();
            } finally {
                DataSourceContextHolder.clearDataSourceKey();
            }
        } else {
            return supplier.get();
        }
    }

    public void addDataSource(String key, DataSource dataSource) {
        dynamicDataSource.addTargetDataSource(key, dataSource);
    }

    public void removeDataSource(String key) {
        dynamicDataSource.removeTargetDataSource(key);
    }
}